第 7 章:創造工作空間 workspace
前一回我們建立多個資料夾來管理不同工作環境下的狀態記錄,這樣的做法讓我們在實作工作上有更多的運用空間。
其實 Terraform 還有一個工具可以幫忙處理這樣的情況,就是工作空間 (Workspace)。你可能在之前的練習打指令的過程中有注意到它,現在我們就來聊聊工作空間 (Workspace) 可以辦到哪些事情。
指令 workspace
首先進入一個 Terrform 的工作資料夾裡,執行以下指令:
terraform workspace list
* default
你可以看終端機上印出了一個 *
號跟 default
:
- 標示著目前的工作空間
default
是預設的工作空間名稱
當我們沒有使用認何的工作空間功能時,預設只有一個 default
的工作空間。
用 -h
看完整的指令說明:
terraform workspace -h
Usage: terraform workspace
new, list, show, select and delete Terraform workspaces.
Subcommands:
delete Delete a workspace
list List Workspaces
new Create a new workspace
select Select a workspace
show Show the name of the current workspace
我們可以用 new
建立工作空間,然後使用 select
切換。
工作空間變數
工作空間有一個特別的變數 ${terraform.workspace}
可以在組態檔中使用,這個變數會取得目前的工作空間名稱。
測試用組態檔
terraform configuration file
resource "aws_instance" "example" {
ami = "ami-0461b11e2fad8c14a"
instance_type = var.instance_type
tags = {
Name = "web - ${terraform.workspace}"
Terraform = "true"
Environment = terraform.workspace
}
}
output "instance_type" {
value = aws_instance.example.instance_type
}
output "instance_name" {
value = aws_instance.example.tags.Name
}
這份組態檔有使用到前面提到的變數 ${terraform.workspace}
。
完整的檔案內容可以在 Github 上看到。
建立 dev 工作空間
執行指令建立 dev 工作空間,你會看到以下訊息:
terraform workspace new dev
Created and switched to workspace "dev"!
You're now on a new, empty workspace. Workspaces isolate their state,
so if you run "terraform plan" Terraform will not see any existing state
for this configuration.
執行 apply
使用 -var-file
帶入 dev 的變數檔 dev.tfvars
,你會看到終端機印出工作空間是 dev 的訊息。
輸出的結果中,我們看到 instance_name
也加上工作空間名稱 dev
。
terraform apply -var-file=dev.tfvars
...
Do you want to perform these actions in workspace "dev"?
...
Outputs:
instance_name = web - dev
instance_type = t2.micro
執行 show
指令,可以看到目前的狀態資料。
terraform show
# aws_instance.example:resource "aws_instance" "example" {
}
建立 qa 工作空間
執行指令建立 dev 工作空間,你會看到以下訊息:
terraform workspace new qa
Created and switched to workspace "qa"!
You're now on a new, empty workspace. Workspaces isolate their state,
so if you run "terraform plan" Terraform will not see any existing state
for this configuration.
執行 show
指令,可以看到目前沒有任何狀態資料,我們切換到一個乾淨的工作空間了。
terraform show
No state.
執行 apply
使用 -var-file
帶入 qa 的變數檔 qa.tfvars
。
輸出的結果中, instance_name
加上工作空間名稱 qa
。
terraform apply -var-file=qa.tfvars
Outputs:
instance_name = web - qa
instance_type = t3.micro